/**
 * 系统配置模块 - 账号信息和主题设置
 * 处理账号信息展示、主题切换等功能
 */

// 初始化账号信息标签页
function initAccountInfoTab() {
    console.log('初始化账号信息标签页');

    if (!document.body.classList.contains('account-info-initialized')) {
        setupThemeSwitching();
        setupAccountActions();
        loadAccountInfo();
        document.body.classList.add('account-info-initialized');
    }
}

// 加载保存的主题
function loadSavedTheme() {
    try {
        let theme = localStorage.getItem('preferredTheme') || localStorage.getItem('theme') || 'default';
        console.log('加载保存的主题:', theme);
        applyTheme(theme);
        document.querySelectorAll('.theme-option').forEach(btn => {
            btn.classList.remove('active');
            if (btn.getAttribute('data-theme') === theme) {
                btn.classList.add('active');
            }
        });
    } catch (e) {
        console.error('加载主题失败:', e);
    }
}

// 设置主题切换
function setupThemeSwitching() {
    document.querySelectorAll('.theme-option').forEach(button => {
        button.addEventListener('click', function () {
            const theme = this.getAttribute('data-theme');
            document.querySelectorAll('.theme-option').forEach(btn => btn.classList.remove('active'));
            this.classList.add('active');
            applyTheme(theme);
            saveThemePreference(theme);
        });
    });
}

// 应用主题
function applyTheme(theme) {
    const body = document.body;
    body.className = body.className.replace(/theme-\w+/g, '').trim();
    if (theme !== 'default') {
        body.classList.add(`theme-${theme}`);
    }
    document.documentElement.setAttribute('data-theme', theme);
    // 广播主题变更
    if (typeof BroadcastChannel !== 'undefined') {
        new BroadcastChannel('theme_change').postMessage({ theme: theme });
    }
}

// 保存主题偏好
function saveThemePreference(theme) {
    try {
        localStorage.setItem('preferredTheme', theme);
        if (typeof Android !== 'undefined' && Android.saveThemePreference) {
            Android.saveThemePreference(theme);
        }
        console.log(`主题偏好已保存: ${theme}`);
    } catch (e) {
        console.error('保存主题偏好失败:', e);
    }
}

// 设置账号操作事件
function setupAccountActions() {
    const logoutBtn = document.getElementById('logout-btn');
    if (logoutBtn) {
        logoutBtn.addEventListener('click', showLogoutConfirmation);
    }
}

// 显示退出登录确认
function showLogoutConfirmation() {
    const dialog = document.getElementById('logout-dialog');
    const overlay = document.getElementById('logout-overlay');
    if (!dialog || !overlay) {
        // Fallback to simple confirm if dialog elements are not found
        if (confirm('确定要退出当前账号吗？')) {
            if (window.UserManager) {
                window.UserManager.logout(false);
            }
        }
        return;
    }

    overlay.style.display = 'block';
    dialog.style.display = 'block';
    setTimeout(() => {
        overlay.classList.add('active');
        dialog.classList.add('active');
    }, 10);

    const close = () => {
        overlay.classList.remove('active');
        dialog.classList.remove('active');
        setTimeout(() => {
            overlay.style.display = 'none';
            dialog.style.display = 'none';
        }, 300);
    };

    dialog.querySelector('.close-btn').onclick = close;
    dialog.querySelector('.cancel-btn').onclick = close;
    dialog.querySelector('.save-btn').onclick = () => {
        if (window.UserManager) {
            window.UserManager.logout(true);
        }
        close();
    };
}

// 加载账号信息
function loadAccountInfo() {
    if (window.UserManager) {
        const currentUser = window.UserManager.getCurrentUser();
        if (currentUser) {
            updateAccountInfo(currentUser);
        } else {
            console.warn('无法加载账号信息，用户未登录');
        }
    }
}

// 更新账号信息UI
function updateAccountInfo(data) {
    const usernameEl = document.getElementById('username');
    const roleEl = document.getElementById('role');
    const lastLoginEl = document.getElementById('last-login');

    if (usernameEl) usernameEl.textContent = data.username || 'N/A';
    if (roleEl) roleEl.textContent = data.roleName || 'N/A';
    if (lastLoginEl) lastLoginEl.textContent = data.lastLoginTime || 'N/A';
}

// 页面加载时初始化主题
document.addEventListener('DOMContentLoaded', function() {
    loadSavedTheme();
    
    // 监听主题变更广播
    if (typeof BroadcastChannel !== 'undefined') {
        const themeChannel = new BroadcastChannel('theme_change');
        themeChannel.onmessage = function(e) {
            if (e.data && e.data.theme) {
                applyTheme(e.data.theme);
            }
        };
    }
}); 